package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.xcity.game.task.TaskManager;

import naga.x.util.StringUtils;

/**
 * 任务解析handler
 * { version: 版本号, tasks: [ ...任务列表... ] }
 * @author yang.li
 *
 */
public class TasksTypeHandler extends BaseTypeHandler<TaskManager> {
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, TaskManager parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null ? parameter.toString() : null);
	}

	@Override
	public TaskManager getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public TaskManager getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public TaskManager getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}
	
	private static TaskManager parse(String json) {
		if (StringUtils.isNotEmpty(json)) {
			return JSON.parseObject(json, TaskManager.class);
		}
		return null;
	}
	
}
